package com.aiguigu.gulimall.product.service.impl;

import com.aiguigu.gulimall.product.entity.AdmissionCard;
import com.aiguigu.gulimall.product.entity.ProbQuVo;
import com.aiguigu.gulimall.product.service.ProblemService;
import com.aiguigu.gulimall.product.utils.PdfCreateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.atguigu.common.utils.ExcelMergeUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ProblemServiceImp implements ProblemService {

    @Override
    public void exportQuExcel(HttpServletResponse response) {
        // 获取数据
        List<ProbQuVo> probVos = new ArrayList<>();
        ProbQuVo probQuVo1 = ProbQuVo.builder().projectName("供电局").distname("天宁区").checkTime("2021-01-06 10:15:09").typeName("维护管理制度责任").grade("不合格").build();
        ProbQuVo probQuVo2 = ProbQuVo.builder().projectName("供电局").distname("天宁区").checkTime("2021-01-06 10:15:10").typeName("维护管理制度责任1").grade("不合格").build();
        ProbQuVo probQuVo3 = ProbQuVo.builder().projectName("供电局1").distname("天宁区1").checkTime("2021-01-06 10:15:55").typeName("维护管理制度责任1").grade("不合格").build();
        ProbQuVo probQuVo4 = ProbQuVo.builder().projectName("供电局12").distname("天宁区12").checkTime("2021-01-06 10:15:33").typeName("维护管理制度责任12").grade("不合格").build();
        probVos.add(probQuVo1);
        probVos.add(probQuVo2);
        probVos.add(probQuVo3);
        probVos.add(probQuVo4);

        // 生成自增序号
        for (int i = 0; i < probVos.size(); i++) {
            probVos.get(i).setNumber(i + 1);
        }
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("问题台账", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //需要合并的列
            int[] mergeColumeIndex = {1, 2};
            //从第二行后开始合并
            int mergeRowIndex = 2;
            // 调用合并单元格工具类，此工具类是没有根据合并，数据相同就合并了
            // ExcelFillCellMergeStrategy excelFillCellMergeStrategy = new ExcelFillCellMergeStrategy(mergeRowIndex,mergeColumeIndex);

            // 调用合并单元格工具类，此工具类是根据工程名称相同则合并后面数据
            ExcelMergeUtil excelFillCellMergeStrategy = new ExcelMergeUtil(mergeRowIndex, mergeColumeIndex);
            // 这里需要设置不关闭流
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置背景颜色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            //设置头字体
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 13);
            headWriteFont.setBold(true);
            headWriteCellStyle.setWriteFont(headWriteFont);
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            //内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            //内容自动换行，实体类不能加@ContentRowHeight() 注解，否则会挤压数据，造成行高固定
            contentWriteCellStyle.setWrapped(true);
            contentWriteCellStyle.setShrinkToFit(true);//设置文本收缩至合适
            // 垂直居中
            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            //设置左边框
            contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
            //设置右边框
            contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
            //设置上边框
            contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
            //设置下边框
            contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

            EasyExcel.write(response.getOutputStream(), ProbQuVo.class)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(excelFillCellMergeStrategy)
                    // 导出文件名
                    .autoCloseStream(Boolean.TRUE).sheet("问题台账")
                    .doWrite(probVos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载word
     * @param userId
     * @param response
     */
//    @Override
//    public void generateWordXWPFDocument(Long userId,HttpServletResponse response) {
//        try {
//            XWPFDocument doc = new XWPFDocument();
//            List<ReportDetail>  ReportDetail = reportResultMapper.reportDetails(userId);
//            createParagraph(doc, ReportDetail.get(0).getReport());
//            response.reset();
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-disposition",
//                    "attachment;filename=user_word_" + System.currentTimeMillis() + ".docx");
//            OutputStream os = response.getOutputStream();
//            doc.write(os);
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 下载pdf
     *
     * @param userId
     * @param response
     */
    @Override
    public void generateWordXWPFDocument(HttpServletResponse response) {
        try {

            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=user_pdf_" + System.currentTimeMillis() + ".pdf");

            OutputStream os = response.getOutputStream();
            // document
//            Document document = PdfCreateUtil.getDocumentInstance();
//            PdfCreateUtil.setDocumentProperties(document,"试卷题目","mcj","嗨皮","试卷","mcj");

//            Document document = new Document(PageSize.A4);
            // open
//            document.open();
            // 获取数据
            List<ProbQuVo> probVos = new ArrayList<>();
            ProbQuVo probQuVo1 = ProbQuVo.builder().projectName("供电局").distname("天宁区").checkTime("2021-01-06 10:15:09").typeName("维护管理制度责任").grade("不合格").build();
            ProbQuVo probQuVo2 = ProbQuVo.builder().projectName("供电局").distname("天宁区").checkTime("2021-01-06 10:15:10").typeName("维护管理制度责任1").grade("不合格").build();
            ProbQuVo probQuVo3 = ProbQuVo.builder().projectName("供电局1").distname("天宁区1").checkTime("2021-01-06 10:15:55").typeName("维护管理制度责任1").grade("不合格").build();
            ProbQuVo probQuVo4 = ProbQuVo.builder().projectName("供电局12").distname("天宁区12").checkTime("2021-01-06 10:15:33").typeName("维护管理制度责任12").grade("不合格").build();
            probVos.add(probQuVo1);
            probVos.add(probQuVo2);
            probVos.add(probQuVo3);
            probVos.add(probQuVo4);

            // document
            Document document = PdfCreateUtil.getDocumentInstance();
            PdfWriter.getInstance(document, os);
            PdfCreateUtil.setDocumentProperties(document, "试卷题目", "mcj", "嗨皮", "试卷", "mcj");

            document.open();
            for (ProbQuVo probVo : probVos) {
                String report = probVo.getProjectName();
                Font font = new Font(getBaseFont(), 12, Font.NORMAL);
                Paragraph paragraph = PdfCreateUtil.getParagraph(report, font, 12, 24, 20f);
                document.add(paragraph);
            }
            document.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void generatorAdmissionCard(HttpServletResponse response) throws IOException {
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=examination_" + System.currentTimeMillis() + ".docx");
        OutputStream os = response.getOutputStream();
        // document
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("aaaaaa");
        XWPFParagraph paragraph1 = document.createParagraph();
        XWPFRun run1 = paragraph1.createRun();
        run1.setText("aaaaaabbbbbbbbb");

        document.write(os);
        document.close();
        os.close();
    }

    @Override
    public void exportPdf(HttpServletResponse response) throws DocumentException, FileNotFoundException {
        // 获取数据
        List<ProbQuVo> probVos = new ArrayList<>();
        ProbQuVo probQuVo1 = ProbQuVo.builder().projectName("供电局").distname("天宁区").checkTime("2021-01-06 10:15:09").typeName("维护管理制度责任").grade("不合格").build();
        ProbQuVo probQuVo2 = ProbQuVo.builder().projectName("供电局").distname("天宁区").checkTime("2021-01-06 10:15:10").typeName("维护管理制度责任1").grade("不合格").build();
        ProbQuVo probQuVo3 = ProbQuVo.builder().projectName("供电局1").distname("天宁区1").checkTime("2021-01-06 10:15:55").typeName("维护管理制度责任1").grade("不合格").build();
        ProbQuVo probQuVo4 = ProbQuVo.builder().projectName("供电局12").distname("天宁区12").checkTime("2021-01-06 10:15:33").typeName("维护管理制度责任12").grade("不合格").build();
        probVos.add(probQuVo1);
        probVos.add(probQuVo2);
        probVos.add(probQuVo3);
        probVos.add(probQuVo4);

        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("D:/output.pdf"));
        document.open();


        //
        for (ProbQuVo probVo : probVos) {
            document.add(new Paragraph(probVo.toString()));
        }

        document.close();
    }


    /**
     * 下载word
     *
     * @param doc
     * @param content
     */
    private void createParagraph(XWPFDocument doc, String content) {
        XWPFParagraph actType = doc.createParagraph();
        XWPFRun runText2 = actType.createRun();
        runText2.setText(content);
        runText2.setFontSize(11);
        // 设置段落对齐方式
        actType.setAlignment(ParagraphAlignment.CENTER); // 居中对齐
        actType.setVerticalAlignment(TextAlignment.CENTER); // 垂直居中对齐
    }

    /**
     * 下载pdf
     *
     * @param content
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    private com.itextpdf.text.Paragraph createParagraph(String content) throws IOException, DocumentException {
        Font font = new Font(getBaseFont(), 12, Font.NORMAL);
        Paragraph paragraph = new Paragraph(content, font);
        paragraph.setAlignment(Element.ALIGN_LEFT);
        paragraph.setIndentationLeft(12); //设置左缩进
        paragraph.setIndentationRight(12); //设置右缩进
        paragraph.setFirstLineIndent(24); //设置首行缩进
        paragraph.setLeading(20f); //行间距
        paragraph.setSpacingBefore(5f); //设置段落上空白
        paragraph.setSpacingAfter(10f); //设置段落下空白
        return paragraph;
    }

    private BaseFont getBaseFont() throws IOException, DocumentException {
        return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    }


}
